import React, {PureComponent} from 'react';
import Breadcrumb from 'Shell/components/Breadcrumb';
import {
    getCurrentUserPagePermissionsApi,
} from 'Shared/actions/currentUserContext';
import {Form, Row, Col, Card, Button, Table, Modal} from 'antd';
import TextInput from 'Shared/components/TextInput';
import {FORM_OPTIONS, PAGE, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT, TABLE, PAGINATION_OPTIONS, DATE_FORMAT, DATETIME_FORMAT, FIXED_COLUMN_WIDTH} from '../constants';
import {formatMessage, language} from './intl';
import DropdownMenu from 'Shared/components/DropdownMenu';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {hasPermissions} from './utils';
import Export from '../common/Export';
import {PERMISSION} from './constants';
import {getPartWarrantyCategories, exportPartWarrantyCategory, abandonPartWarrantyCategory} from './api';
import {conventSorter, formatDateTime, conventEnumValueToString} from '../utils';
import styles from './styles.css';
import {baseDataStatus, dealerType} from '../Enum';
import DetailModal from './DetailModal';
import WrappedSelect from '../common/WrappedSelect';
import AddModal from './AddModal';
import EditModal from './EditModal';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import FileImport from './FileImport';

const ButtonGroup = Button.Group;
const FormItem = Form.Item;
export const dealerConditions = {
    type: dealerType.总代
};
export class App extends PureComponent {
    state = {
        code: '',
        name: '',
        dealerId: '',
        dealerCode: '',
        dealerName: '',
        isFetching: false,
        data: {},
        message: '',
        pageIndex: PAGE.index,
        pageSize: PAGE.smallSize,
        currentCondition: {},
        permissions: [],
        showAdd: false,
        showDetail: false,
        showEdit: false,
        showImport: false,
        currentId: null
    }

    componentDidMount() {
        getCurrentUserPagePermissionsApi('dcs-afterSales-partWarrantyCategory').then(res => {
            if(res.isOk)
                this.setState({
                    permissions: res.data
                });
        });
    }
    
    handleFilterPressEnter = (value, name) => {
        this.setState({[name]: value}, this.onClickSearchBtn);
    }

    handleTableChange = (pagination, filters, sorter) => {
        const oldCondition = this.state.currentCondition;
        if(pagination.current - 1 === oldCondition.pageIndex && pagination.pageSize === oldCondition.pageSize) {
            const sortOptions = conventSorter(sorter);
            const condition = Object.assign({}, oldCondition, sortOptions, {
                pageIndex: PAGE.index
            });
            this.onQuery(condition);
            this.setState({sortField: sortOptions.sortField,
                isDesc: sortOptions.isDesc});
        }
    }

    handleAbandon = (id, rowVersion) => {
        this.setState({loading: true});
        abandonPartWarrantyCategory(id, {rowVersion}).then(res => {
            this.setState({loading: false});
            if(res.ok)
                this.onClickSearchBtn();
        });
    }

    onChange = (value, name) => {
        this.setState({[name]: value});
    }
    onSelectDealer = data => {
        this.setState({
            dealerId: data.id,
            dealerCode: data.code,
            dealerName: data.name,
        });
    }
    onQuery = condition => {
        this.setState({isFetching: true});
        getPartWarrantyCategories(condition)
            .then(res => {
                if(res.ok)
                    this.setState({
                        isFetching: false,
                        message: '',
                        data: res.data,
                        currentCondition: condition
                    });
                else
                    this.setState({
                        isFetching: false,
                        data: [],
                        message: res.message
                    });
            });
    }

    onClickSearchBtn = () => {
        const condition = {
            code: this.state.code,
            name: this.state.name,
            dealerId: this.state.dealerId,
            status: this.state.status,
            pageIndex: PAGE.index,
            pageSize: this.state.pageSize,
            sortField: this.state.sortField,
            isDesc: this.state.isDesc
        };
        this.onQuery(condition);
    }

    onPageIndexChange = current => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = current - 1;
        this.onQuery(condition);
    }

    onPageSizeChange = (current, pageSize) => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = PAGE.index;
        condition.pageSize = pageSize;
        this.onQuery(condition);
        this.setState({
            pageSize
        });
    }

    showAdd = () => {
        this.setState({
            showAdd: !this.state.showAdd
        });
    }

    showImport = () => {
        this.setState({
            showImport: !this.state.showImport
        });
    }
    showDetail = e => {
        const id = e ? e.target.dataset.id : null;
        this.setState({
            currentId: id,
            showDetail: !this.state.showDetail
        });
    }
    showEdit = e => {
        const id = e ? e.target.dataset.id : null;
        this.setState({
            currentId: id,
            showEdit: !this.state.showEdit
        });
    }

    render() {
        const {code, name, status, isFetching, data, message, loading} = this.state;
        const {pageIndex, pageSize} = this.state.currentCondition;
        const dealerInfo = this.state.dealerId ? {
            id: this.state.dealerId,
            code: this.state.dealerCode,
            name: this.state.dealerName
        } : null;
        const operations = [];
        const otherBtns = [];

        if(hasPermissions(this.state.permissions, PERMISSION.import))
            otherBtns.push(<Button key="import" onClick={this.showImport}>{formatMessage({
                id: 'app.btn.import',
                defaultMessage: '导入'
            })}</Button>);
        if(hasPermissions(this.state.permissions, PERMISSION.export))
            otherBtns.push(<Export key={PERMISSION.export} exportRequest={exportPartWarrantyCategory} />);
        if(hasPermissions(this.state.permissions, PERMISSION.add))
            operations.push(<Button key="add" type="primary" onClick={this.showAdd}>{formatMessage({
                id: 'app.btn.add',
                defaultMessage: '新增'
            })}</Button>);

        const columns = [{
            title: formatMessage({
                id: 'app.columns.dealer',
                defaultMessage: '总代'
            }),
            dataIndex: 'dealerCode',
            render: (text, r) => `(${r.dealerCode})${r.dealerName}`
        }, {
            title: formatMessage({
                id: 'app.columns.code',
                defaultMessage: '编号'
            }),
            dataIndex: 'code',
            sorter: true,
            render: (text, record) => <a data-id={record.id} onClick={this.showDetail}>{text}</a>
        }, {
            title: formatMessage({
                id: 'app.columns.name',
                defaultMessage: '名称'
            }),
            dataIndex: 'name',
        }, {
            title: formatMessage({
                id: 'app.columns.status',
                defaultMessage: '状态'
            }),
            dataIndex: 'status',
            sorter: true,
            render: text => conventEnumValueToString(baseDataStatus, text)
        }, {
            title: formatMessage({
                id: 'app.columns.createTime',
                defaultMessage: '创建时间'
            }),
            dataIndex: 'createTime',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: formatMessage({
                id: 'app.column.action',
                defaultMessage: '操作'
            }),
            dataIndex: 'action',
            width: FIXED_COLUMN_WIDTH,
            fixed: 'right',
            render: (t, r) => {
                const menus = [{
                    id: PERMISSION.update,
                    children: <a data-id={r.id} key="update" onClick={this.showEdit}>
                        {formatMessage({
                            id: 'app.operation.update',
                            defaultMessage: '编辑'
                        })}</a>,
                    hidden: !(hasPermissions(this.state.permissions, PERMISSION.update) &&
                            hasPermissions(r.options, PERMISSION.update)),
                }, {
                    id: PERMISSION.abandon,
                    children: ref => <WrappedPopconfirm id={r.id} key="abandon" title={formatMessage({
                        id: 'app.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })} onVisibleChange={ref.setMenuVisible} onConfirm={() => this.handleAbandon(r.id, r.rowVersion)}>
                        <a key="abandon">{formatMessage({
                            id: 'app.operation.abandon',
                            defaultMessage: '作废'
                        })}</a>
                    </WrappedPopconfirm>,
                    hidden: !(hasPermissions(this.state.permissions, PERMISSION.abandon) &&
                                hasPermissions(r.options, PERMISSION.abandon)),
                }];
                return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
            }
        }];
        const pagination = {
            total: data.totalElements,
            current: pageIndex + 1,
            pageSize,
            onShowSizeChange: this.onPageSizeChange,
            onChange: this.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        return (
            <div>
                <Breadcrumb />
                <div className="page-main">
                    <Card>
                        <Form className="form-standard">
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'app.form.dealerId',
                                            defaultMessage: '总代'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <DealerSelectPanel
                                            value={dealerInfo}
                                            conditions={dealerConditions}
                                            onSelect={this.onSelectDealer} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'app.form.code',
                                            defaultMessage: '编号'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="code"
                                            value={code}
                                            onPressEnter={this.handleFilterPressEnter}
                                            onBlur={this.onChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'app.form.name',
                                            defaultMessage: '名称'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="name"
                                            value={name}
                                            onPressEnter={this.handleFilterPressEnter}
                                            onBlur={this.onChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'app.form.status',
                                            defaultMessage: '状态'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <WrappedSelect
                                            allowClear
                                            name="status"
                                            value={status}
                                            options={baseDataStatus.toList(language)}
                                            onChange={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row className="operation-buttons">
                                <Col span={6}>
                                    <Button key="query" type="primary" disabled={this.state.disableQueryBtn}
                                        onClick={this.onClickSearchBtn} loading={this.state.isFetching}>{formatMessage({
                                            id: 'app.btn.query',
                                            defaultMessage: '查询'
                                        })}</Button>
                                    <Button key="clear" onClick={this.props.onClickReset}>{formatMessage({
                                        id: 'app.btn.reset',
                                        defaultMessage: '重置'
                                    })}</Button>
                                </Col>
                                <Col span={18} className="col-align-right">
                                    <ButtonGroup>{otherBtns}</ButtonGroup>
                                    {operations}
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card>
                        <Table
                            className={`white-space-nowrap ${styles.tableCursor}`}
                            rowKey="id"
                            dataSource={data.content}
                            columns={columns}
                            loading={isFetching || loading}
                            pagination={pagination}
                            onChange={this.handleTableChange}
                            {...TABLE}
                            locale={{
                                emptyText: message ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
                            }} />
                    </Card>
                </div>
                <DetailModal id={this.state.currentId}
                    visible={this.state.showDetail} onCancel={this.showDetail} />
                <AddModal visible={this.state.showAdd} afterSubmit={this.onClickSearchBtn} onCancel={this.showAdd} />
                <EditModal id={this.state.currentId} afterSubmit={this.onClickSearchBtn}
                    visible={this.state.showEdit} onCancel={this.showEdit} />
                <Modal
                    title={formatMessage({
                        id: 'importModal.modal.title',
                        defaultMessage: '导入'
                    })}
                    width="60%"
                    footer={null}
                    maskClosable={false}
                    visible={this.state.showImport}
                    destroyOnClose={true}
                    onCancel={this.showImport}>
                    <FileImport afterImport={this.onClickSearchBtn} />
                </Modal>
            </div>
        );
    }
}

export default App;
